package models

import (
	// "errors"
	"fmt"

	"gitee.com/lzqysoft/goadmin/libs/cache"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	// "reflect"
	// "strings"
	"time"
)

type Temp struct {
	Id       string    `orm:"column(id);pk"`
	Name     string    `orm:"column(name)"`
	Remark   string    `orm:"column(remark);null"`
	Status   int       `orm:"column(status)"`
	Isdelete int       `orm:"column(isdelete)"`
	Ctime    time.Time `orm:"column(ctime);type(timestamp without time zone)"`
	Creater  string    `orm:"column(creater);null"`
	Utime    time.Time `orm:"column(utime);type(timestamp without time zone)"`
	Updater  string    `orm:"column(updater);null"`
}

func (t *Temp) TableName() string {
	return "yjk_temp"
}

func init() {
	orm.RegisterModel(new(Temp))
}

// AddTemp insert a new Temp into database and returns
// last inserted Id on success.
func AddTemp(m *Temp) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	cid := "GetAllTemp"
	cache.DelCache(cid)
	return
}

// GetTempById retrieves Temp by Id. Returns error if
// Id doesn't exist
func GetTempById(id string) (v *Temp, err error) {
	o := orm.NewOrm()
	v = &Temp{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllTemp retrieves all Temp matches certain condition. Returns empty list if
// no records exist
func GetAllTemp() (ml []orm.Params, err error) {
	cid := "GetAllTemp"
	err = cache.GetCache(cid, &ml)
	if err != nil {
		o := orm.NewOrm()
		qs := o.QueryTable(new(Temp)).Filter("Isdelete", 0).Filter("Status", 1).Limit(-1)
		_, err = qs.Values(&ml)
		cache_expire, _ := beego.AppConfig.Int("cache_expire")
		cache.SetCache(cid, ml, cache_expire)
	}

	return
}

// UpdateTemp updates Temp by Id and returns error if
// the record to be updated doesn't exist
func UpdateTempById(m *Temp) (err error) {
	o := orm.NewOrm()
	v := Temp{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	cid := "GetAllTemp"
	cache.DelCache(cid)
	return
}

// DeleteTemp deletes Temp by Id and returns error if
// the record to be deleted doesn't exist
func DeleteTemp(id string) (err error) {
	o := orm.NewOrm()
	v := Temp{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&Temp{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	cid := "GetAllTemp"
	cache.DelCache(cid)
	return
}

// SoftDeleteTemp 软删除 Temp
func SoftDeleteTemp(id string, uname string) (err error) {
	o := orm.NewOrm()
	v := Temp{Id: id}
	if err = o.Read(&v); err == nil {
		v.Isdelete = 1
		v.Updater = uname
		v.Utime = time.Now()
		_, err = o.Update(&v)
	}
	cid := "GetAllTemp"
	cache.DelCache(cid)
	return
}
